package com.doxiaopu.students.ws;

import com.alibaba.fastjson.JSON;
import com.doxiaopu.students.utils.GetIdUtil;
import com.doxiaopu.students.utils.MessageUtils;
import com.doxiaopu.students.ws.pojo.Message;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/chat/{token}")//encoders = {ServerEncoder.class}用于指定sendObject()方法调用的解析器
@Component
public class  ChatEndpoint {
    //用来存储每一个客户端对象对应的ChatEndpoint对象
    private static final Map<String,Session> onlineusers = new ConcurrentHashMap<>();
    private HttpSession httpSession;
    //声明session对象，通过该对象可以发送信息给指定的用户
    private Session session;

    @OnOpen
    public void onOpen(@PathParam(value = "token") String token, Session session){
        // 获取httpSession对象
        GetIdUtil getIdUtil = new GetIdUtil();

        System.err.print("token:"+token);
//        System.err.print("id:"+getIdUtil.getUidFromRequest(token));
        this.session = session;
        String username = token;
        // 将当前对象存储在容器中
        onlineusers.put(username,session);
        //获取消息
        String message = MessageUtils.getMessage(true,null,getFriends());
        //调用方法进行系统消息的推送
        broadcastAllUsers(message);
    };



    public Set getFriends(){
        Set<String> set = onlineusers.keySet();
        return set;
    }

    private void broadcastAllUsers(String message){
        try {
            //将该消息发送给所有客户端
//            Set<String> names = onlineusers.keySet();
//            for (String name : names){
//                ChatEndpoint chatEndpoint = (ChatEndpoint) onlineusers.get(name);
//                chatEndpoint.session.getBasicRemote().sendText(message);
//            }

            Set<Map.Entry<String,Session>> entries = onlineusers.entrySet();
            for(Map.Entry<String,Session> entry : entries) {
                Session session = entry.getValue();
                session.getBasicRemote().sendText(message);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 浏览器发到服务器，该方法被调用
     * @param message
     */
    @OnMessage
    public void onMessage(@PathParam(value = "token") String token,String message){
        System.err.print(message);
        System.err.print("发送者信息："+token);
        try {
            //将消息推送给指定的用户
            Message msg = JSON.parseObject(message, Message.class);
            System.err.print(msg);
            //数据发送给接收者
            String toName = msg.getToName();
            String mess = msg.getMessage();
            Session session = onlineusers.get(toName);
            //获取当前登录信息的用户名
//            String username = (String)this.httpSession.getAttribute("username");
            //获取推送信息的格式
            String msg1 = MessageUtils.getMessage(false,token,mess);
            //发送数据
            session.getBasicRemote().sendText(msg1);
        } catch (IOException e) {
            e.printStackTrace();
        }
    };

    /**
     * 断开websocket时被调用
     * @param session
     */
    @OnClose
    public void onClose(@PathParam(value = "token") String token,Session session){
//        String username = (String)this.httpSession.getAttribute("username");
        System.err.print("移除："+token);
        onlineusers.remove(token);
        String message = MessageUtils.getMessage(true,null,getFriends());
        broadcastAllUsers(message);
    };
}
